/*
 * Ext4Utils.cpp
 *
 *  Created on: 2018年9月11日
 *      Author: guoxs
 */

#include <sys/mount.h>
#include <sys/statfs.h>
#include <errno.h>
#include <string.h>

#include "utils/Ext4Utils.h"
#include "ext4_utils/make_ext4fs.h"
#include "utils/Log.h"

#define MMCBLK0			"/dev/block/mmcblk0"
#define MOUNT_POINT		"/mnt/extsd"

bool Ext4Utils::isExt4Fs() {
	struct statfs buf;
	if (statfs(MOUNT_POINT, &buf)) {
		LOGE("%s statfs error: %s\n", MOUNT_POINT, strerror(errno));
		return false;
	}

	LOGD("buf.f_type %x\n", buf.f_type);
	return buf.f_type == 0xEF53;
}

bool Ext4Utils::format() {
	LOGD("Ext4Utils format\n");
	return make_ext4fs(MMCBLK0, 0, NULL, NULL) == 0;
}

bool Ext4Utils::mount() {
	if (ismounted()) {
		return true;
	}

	unsigned long flags = MS_NODEV | MS_NOSUID | MS_DIRSYNC;

	int ret = ::mount(MMCBLK0, MOUNT_POINT, "ext4", flags, NULL);
	LOGD("Ext4Utils mount ret %d\n", ret);
	if (ret) {
		LOGE("Ext4Utils mount errno : %s\n", strerror(errno));
	}

	return ret == 0;
}

bool Ext4Utils::umount() {
	if (!ismounted()) {
		return true;
	}

	int ret = ::umount(MOUNT_POINT);
	LOGD("Ext4Utils umount ret %d\n", ret);
	if (ret) {
		LOGE("Ext4Utils umount errno : %s\n", strerror(errno));
	}

	return ret == 0;
}

bool Ext4Utils::ismounted() {
	const char *proc = "/proc/mounts";
	FILE *fp;
	if (!(fp = fopen(proc, "r"))) {
		printf("%s open fail!!!\n", proc);
		return false;
	}

	bool ret = false;
	char line[256] = { 0 };

	while (fgets(line, sizeof(line), fp)) {
		if (strstr(line, MOUNT_POINT)) {
			ret = true;
			break;
		}
	}

	fclose(fp);

	return ret;
}
